package com.yilei.testninegridview

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.yilei.testninegridview.MyUtils.setOnSafeClickListener

class NineGridAdapter(
    private val imageUrls: MutableList<String>,
    private val onImageClick: (Int) -> Unit,
    private val onAddImageClick: () -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val VIEW_TYPE_IMAGE = 0
    private val VIEW_TYPE_INFO = 1

    override fun getItemViewType(position: Int): Int {
        return if (position == imageUrls.size) VIEW_TYPE_INFO else VIEW_TYPE_IMAGE
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == VIEW_TYPE_IMAGE) {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_image, parent, false)
            ImageViewHolder(view)
        } else {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_info, parent, false)
            InfoViewHolder(view)
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is ImageViewHolder) {
            val imageUrl = imageUrls[position]
            Glide.with(holder.itemView.context)
                .load(imageUrl)
                .into(holder.imageView)

            holder.imageView.setOnSafeClickListener {
                onImageClick(position) // 点击图片的事件
            }
        } else if (holder is InfoViewHolder) {
            holder.infoTextView.text = "这是信息文本" // 设置 infoTextView 的文本
            holder.infoTextView.setOnSafeClickListener {
                onAddImageClick()
            }
        }
    }
    fun updateImageUrls(urls: List<String>){
        this.imageUrls.addAll(urls)
    }
    override fun getItemCount(): Int {
        return imageUrls.size + 1 // 多加一项用于 infoTextView
    }

    class ImageViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val imageView: ImageView = view.findViewById(R.id.imageView)
    }

    class InfoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val infoTextView: TextView = view.findViewById(R.id.infoTextView)
    }
}
